package com.linjacy.container.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.linjacy.common.utils.R;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linjacy.common.utils.PageUtils;
import com.linjacy.common.utils.Query;

import com.linjacy.container.product.dao.UserDao;
import com.linjacy.container.product.entity.UserEntity;
import com.linjacy.container.product.service.UserService;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {
    Long use;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UserEntity> page = this.page(
                new Query<UserEntity>().getPage(params),
                new QueryWrapper<UserEntity>().select("distinct uid,uname,address,phone_num,email,is_order")
        );
        return new PageUtils(page);
    }

    @Override
    public void updateByTableId(UserEntity user) {
        String uname = user.getUname();
        List<UserEntity> entities = baseMapper.selectList(new QueryWrapper<UserEntity>().eq("uname", uname));
        List<Long> collect = entities.stream().map(item -> {
            return item.getTableid();
        }).collect(Collectors.toList());
        for (Long aLong : collect) {
            user.setTableid(aLong);
            System.out.println(aLong);
            int i = baseMapper.updateById(user);
        }

    }


    @Override
    public void saveAuto(UserEntity user) {
        getUid();
        user.setUid(use);
        save(user);
    }

    @Override
    public void removeByUid(Long id) {
        QueryWrapper<UserEntity> wrapper=new QueryWrapper();
        wrapper.eq("uid",id);
        List<UserEntity> userEntities = baseMapper.selectList(wrapper);
        List<Long> collect = userEntities.stream().map(item -> {
            return item.getTableid();
        }).collect(Collectors.toList());
        for (Long aLong : collect) {
            baseMapper.deleteById(aLong);
        }
    }

    public void getUid() {
        Random random = new Random();
        Integer i = random.nextInt(10000);
        long l = i.longValue();
        Integer uid = baseMapper.selectCount(new QueryWrapper<UserEntity>().eq("uid", l));
        if(uid==0){
            use=l;
        }else{
            getUid();
        }
    }
}

